/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */
import { findTargetProduct } from '../../common/find-target-product.js';
import { CompileModeEnum } from '../../enum/compile-mode-enum.js';
import { ApiType } from '../../project/data/hap-extra-info.js';
import { ErrorUrl } from '../../utils/error-url.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { resolveHookDependency } from '../../utils/task-util.js';
import { TaskNames } from '../common/task-names.js';
import { CompileResource } from '../compile-resource.js';
import { GenerateLoaderJson } from '../generate-loader-json.js';
import { AbstractModuleHookTask } from '../hook/abstract-module-hook-task.js';
import { ModuleTaskService } from '../service/module-task-service.js';
import { TargetTaskService } from '../service/target-task-service.js';

/**
 * 提供调用hot reload的前置task
 */
export class BuildHotReloadResource extends AbstractModuleHookTask {
  private _log: OhosLogger = OhosLogger.getLogger(BuildHotReloadResource.name);

  constructor(moduleTaskService: ModuleTaskService) {
    super(moduleTaskService, false, TaskNames.CommonHookTask.BUILD_HOT_RELOAD_RES);
  }

  // override
  registryAction = (): Function => {
    const moduleModel = this._moduleService.getModuleModel();
    const productBuildOpt = findTargetProduct(moduleModel.getParentProject());
    const apiVersion: number = moduleModel.getCompileApiMetaByProduct(productBuildOpt.name).version;
    return () => {
      if (moduleModel.getCompileMode(productBuildOpt) !== CompileModeEnum.ES_MODULE || moduleModel.getApiType() !== ApiType.STAGE || apiVersion < 9) {
        this._log
          .printErrorExit(
            'HOT_RELOAD_PROHIBIT',
            [moduleModel.getProfilePath()],
            [[ErrorUrl.ERROR_URL.hotReload]]
          );
      }
      this._log.debug('Hot reload resources ready.');
    };
  };

  initTaskDepends(taskTargetService: TargetTaskService): void {
    this.dependsOn(resolveHookDependency(GenerateLoaderJson.name, taskTargetService.getTargetData().getTargetName()));
    this.dependsOn(resolveHookDependency(CompileResource.name, taskTargetService.getTargetData().getTargetName()));
  }
}
